//
//  Extensions.swift
//  CMB250716
//
//  Created by Trae AI on [current date].

import SwiftUI
import Foundation

extension View {
    @ViewBuilder func applyIfAvailable<T: View>(@ViewBuilder _ transform: (Self) -> T) -> some View {
        if #available(iOS 16.0, *) {
            transform(self)
        } else {
            self
        }
    }
    
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape(RoundedCorner(radius: radius, corners: corners))
    }
    
    func placeholder<Content: View>(
        when shouldShow: Bool,
        alignment: Alignment = .leading,
        @ViewBuilder placeholder: () -> Content) -> some View {
        
        // 优化版本：减少视图层级，提升首次渲染性能
        ZStack(alignment: alignment) {
            if shouldShow {
                placeholder()
            }
            self
        }
    }
    
    /// 添加点击空白区域收起键盘的功能
    func dismissKeyboardOnTap() -> some View {
        self.onTapGesture {
            hideKeyboard()
        }
    }
    
    /// 为视图添加点击背景收起键盘的功能
    func dismissKeyboardOnBackgroundTap() -> some View {
        self.modifier(DismissKeyboardOnTap())
    }
    
    /// 隐藏键盘的私有方法
    private func hideKeyboard() {
        #if canImport(UIKit)
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        #endif
    }
}

struct RoundedCorner: Shape {
    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(
            roundedRect: rect,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        )
        return Path(path.cgPath)
    }
}

// MARK: - Background Tap Gesture Modifier
struct DismissKeyboardOnTap: ViewModifier {
    func body(content: Content) -> some View {
        content
            .background(
                Color.clear
                    .contentShape(Rectangle())
                    .onTapGesture {
                        hideKeyboard()
                    }
            )
    }
    
    private func hideKeyboard() {
        #if canImport(UIKit)
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        #endif
    }
}

extension Text {
    func weighted(_ weight: Font.Weight) -> Text {
        if #available(iOS 16.0, *) {
            return self.fontWeight(weight)
        } else {
            switch weight {
            case .bold, .heavy, .black:
                return self.bold()
            case .semibold, .medium:
                return self.font(.body)
            default:
                return self
            }
        }
    }
}

// MARK: - MembershipLevel Extensions
extension MembershipLevel {
    static func getDisplayName(for englishName: String, language: String) -> String? {
        let level = MembershipLevel.allCases.first { $0.englishName == englishName }
        switch language {
        case "zh":
            return level?.displayName
        case "en":
            return level?.englishDisplayName
        default:
            return level?.displayName
        }
    }
}

// MARK: - DataManager Extension
extension DataManager {
    /// 获取排序后的可用优惠券列表
    public func getSortedAvailableCoupons() -> [Coupon] {
        let allCoupons = getAllCouponsForDisplay()
        
        return allCoupons.sorted { coupon1, coupon2 in
            let isUnlocked1 = isUserCouponUnlocked(coupon1)
            let isUnlocked2 = isUserCouponUnlocked(coupon2)
            
            // 首先按解锁状态排序：已解锁的排在未解锁的前面
            if isUnlocked1 != isUnlocked2 {
                return isUnlocked1
            }
            
            // 如果解锁状态相同，再按激活状态排序
            let activationStatus1 = checkCouponActivation(coupon: coupon1)
            let activationStatus2 = checkCouponActivation(coupon: coupon2)
            
            let isActivated1 = activationStatus1 == .available
            let isActivated2 = activationStatus2 == .available
            
            if isActivated1 != isActivated2 {
                return isActivated1
            }
            
            // 如果解锁和激活状态都相同，保持原有顺序
            return false
        }
    }
    
    /// 检查优惠券激活状态
    public func checkCouponActivation(coupon: Coupon) -> CouponActivationStatus {
        // 使用统一的解锁条件检查
        let unlockCondition = CouponConfig.UnlockConditions.getUnlockConditionType(
            for: coupon.code,
            user: currentUser,
            dataManager: self
        )
        
        // 将UnlockConditionType转换为CouponActivationStatus
        switch unlockCondition {
        case .loginRequired:
            return .requiresLogin
        case .membershipLevel(_):
            return .requiresMembershipLevel
        case .timeSlotRestricted:
            return .outsideTimeSlot
        case .memberInfoComplete, .birthdayMonthRequired, .activationConditions(_), .usageLimitReached, .usageFrequencyReached, .expired, .inactive:
            return .notActivated
        case .none:
            return .available
        }
    }
    
    /// 获取现金券数量
    public func getCashVoucherQuantityByTitle(_ title: String) -> Int {
        guard let user = currentUser else { return 0 }
        
        // 根据标题找到对应的优惠券代码
        if let coupon = availableCoupons.first(where: { $0.title == title }) {
            // 获取用户拥有的该类型现金券的未使用数量
            let ownedCount = user.ownedCoupons.filter { userCoupon in
                userCoupon.couponCode == coupon.code &&
                !userCoupon.isUsed &&
                userCoupon.expiryDate > Date()
            }.count
            
            return ownedCount
        }
        
        return 0
    }
}

enum CouponActivationStatus {
    case available
    case requiresLogin
    case requiresMembershipLevel
    case outsideTimeSlot
    case notActivated
}

// MARK: - Coupon Extension for UI Helpers
extension Coupon {
    /// 获取标签颜色
    func getTagColor() -> Color {
        return CouponTheme.getTagBackgroundColor(for: self.title)
    }
    
    /// 获取按钮颜色
    func getButtonColor() -> Color {
        return CouponTheme.getButtonBackgroundColor(for: self.title)
    }
    
    /// 获取标签文本颜色
    func getTagTextColor() -> Color {
        return CouponTheme.getTagTextColor(for: self.title)
    }
    
    /// 获取按钮文本颜色
    func getButtonTextColor() -> Color {
        return CouponTheme.getButtonTextColor(for: self.title)
    }
    
    /// 格式化优惠券价值
    func formatValue() -> String {
        switch self.discountType {
        case .percentage:
            return "\(Int(self.discountValue))%"
        case .fixedAmount:
            if self.discountValue == 0 {
                // 对于神秘礼品优惠券，不显示"Free"标签，避免重复
                if self.title == "小牛「神秘礼品」" || self.title == "Calf 'Mystery Gift'" {
                    return ""
                }
                return "Free"
            } else {
                return "S$\(Int(self.discountValue))"
            }
        }
    }
    
    /// 格式化静态优惠券有效期
    func formatStaticValidUntil(language: String) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .none
        
        // 检查是否为长期有效优惠券（2070年以后的日期视为长期有效）
        let calendar = Calendar.current
        let year = calendar.component(.year, from: self.validUntil)
        
        if year >= 2070 {
            // 长期有效优惠券显示"N/A (长期有效)"
            return language == "zh" ? "N/A (长期有效)" : "N/A (Long-term valid)"
        } else {
            let validUntilText = language == "zh" ? "有效期至" : "Valid until"
            return "\(validUntilText) \(formatter.string(from: self.validUntil))"
        }
    }
}

extension Coupon {
    /// 判断是否为现金券
    var isCashVoucher: Bool {
        return title.contains("现金券") || title.contains("Cash Voucher") || title.contains("超值现金礼券")
    }
    
    func formattedTitle(language: String) -> String {
        switch language {
        case "zh":
            return title
        case "en":
            // 使用englishTitle字段，如果没有则回退到原来的硬编码映射
            if !englishTitle.isEmpty {
                return englishTitle
            } else {
                // 回退到硬编码映射以保持兼容性
                switch title {
                case "新会员立减福利":
                    return "New Member Discount"
                case "小牛会员福利":
                    return "Bull Member Benefits"
                case "超值礼券配套":
                    return "Value Voucher Package"
                case "会员周末专享":
                    return "Weekend Member Exclusive"
                case "会员 HighBall专享":
                    return "Member HighBall Exclusive"
                case "小牛欢迎咖啡":
                    return "Bull Welcome Coffee"
                case "小牛「神秘礼品」":
                    return "Bull Mystery Gift"
                case "资料完善专属福利":
                    return "Profile Completion Benefit"
                case "生日月份专属福利":
                    return "Birthday Month Exclusive"
                case "会员信息完善礼券":
                    return "Member Info Completion Voucher"
                case "现金券 S$10":
                    return "Cash Voucher S$10"
                case "现金券 S$20":
                    return "Cash Voucher S$20"
                case "现金券 S$30":
                    return "Cash Voucher S$30"
                case "超值现金礼券 S$10":
                    return "Value Cash Voucher S$10"
                case "超值现金礼券 S$20":
                    return "Value Cash Voucher S$20"
                case "超值现金礼券 S$30":
                    return "Value Cash Voucher S$30"
                case "现金券 1":
                    return "Cash Voucher 1"
                case "现金券 2":
                    return "Cash Voucher 2"
                case "现金券 3":
                    return "Cash Voucher 3"
                default:
                    return title
                }
            }
        default:
            return title
        }
    }
    
    // 统一的渐变颜色获取方法
    func getGradientColors() -> [Color] {
        return CouponTheme.getGradientColors(for: self.title)
    }
    
    func formattedRemarks(language: String, displayTitle: String? = nil) -> String {
        let titleToMatch = displayTitle ?? self.title
        
        if language == "zh" {
            // 中文显示时，使用description字段，如果没有则回退到硬编码
            if !description.isEmpty {
                return description
            } else {
                // 回退到硬编码映射以保持兼容性
                switch self.title {
                case "新会员立减福利":
                    return "首单立减 S$5"
                case "超值礼券配套":
                    return "全场 15% 折扣"
                case "会员周末专享":
                    return "周末全场 50% 折扣"
                case "会员 HighBall专享":
                    return "HighBall 或 Whiskey 免费 （原价 S$10/杯）"
                case "小牛欢迎咖啡":
                    return "免费咖啡（每周一杯）"
                case "小牛「神秘礼品」":
                    return "免费神秘礼品"
                case "燃动打卡券":
                    return "全场立减 S$7"
                case "紫域主理人专享":
                    return "全场立减 S$5"
                case "橙燃玩家专享":
                    return "购买满S$20享受10%折扣"
                case "会员信息完善礼券":
                    return "完善信息立减 S$3"
                case "资料完善专属福利":
                    return "全场立减 S$5"
                case "生日月份专属福利":
                    return "生日月全场 30% 折扣"
                case "小牛会员福利":
                    return "全场 20% 折扣"
                case "现金券 S$10":
                    return "现金抵扣券 S$10"
                case "现金券 S$20":
                    return "现金抵扣券 S$20"
                case "现金券 S$30":
                    return "现金抵扣券 S$30"
                default:
                    return "优惠详情"
                }
            }
        } else {
            // 英文显示时，使用englishDescription字段，如果没有则回退到硬编码
            if !englishDescription.isEmpty {
                return englishDescription
            } else {
                // 回退到硬编码映射以保持兼容性
                switch titleToMatch {
                case "New Member Discount", "新会员立减福利":
                    return "S$5 off first order"
                case "Value Coupon Pack", "超值礼券配套":
                    return "15% off sitewide"
                case "Weekend Exclusive for Members", "会员周末专享":
                    return "50% off sitewide on weekends"
                case "HighBall Member Exclusive", "会员 HighBall专享":
                    return "Free HighBall or Whiskey (U.P. S$10/glass)"
                case "Calf Welcome Coffee", "小牛欢迎咖啡":
                    return "Free coffee (one cup per week)"
                case "Calf 'Mystery Gift'", "小牛「神秘礼品」":
                    return "Free mystery gift"
                case "Fuel Up Streak", "燃动打卡券":
                    return "S$7 off sitewide"
                case "Vibe Regent Exclusive", "紫域主理人专享":
                    return "S$5 off sitewide"
                case "Hype Blaze Exclusive", "橙燃玩家专享":
                    return "10% off when spending S$20 or more"
                case "Member Info Completion", "会员信息完善礼券":
                    return "S$3 off for completing info"
                case "Profile Completion Reward", "资料完善专属福利":
                    return "S$5 off sitewide"
                case "Birthday Month Reward", "生日月份专属福利":
                    return "30% off sitewide in birthday month"
                case "Calf Member Benefit", "小牛会员福利":
                    return "20% off sitewide"
                case "Cash Voucher S$10", "现金券 S$10":
                    return "Cash voucher S$10"
                case "Cash Voucher S$20", "现金券 S$20":
                    return "Cash voucher S$20"
                case "Cash Voucher S$30", "现金券 S$30":
                    return "Cash voucher S$30"
                default:
                    return "Discount details"
                }
            }
        }
    }
}